﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading.Tasks;
using FluentAvalonia.UI.Controls;
using iOSClub.Toolkit.WindowApp.Converters;
using iOSClub.Toolkit.WindowApp.Models;
using Newtonsoft.Json;
using Toolkit.Lib.iOSModels;

namespace iOSClub.Toolkit.WindowApp.ViewModels.Pages;

public class iOSManagerPageModel : PageModelBase
{
    /// <summary>
    /// https://localhost:44347/
    /// https://api.xauat.site
    /// </summary>
    private const string _url = "https://localhost:44347/api";

    private string _jwt = "";

    private string Jwt
    {
        get => _jwt;
        set
        {
            if (string.IsNullOrEmpty(value)) return;
            _jwt = value;
            Login();
        }
    }

    public ObservableCollection<iOSManageItem> Items { get; set; } = new();
    private iOSManageItem _interface = iOSManageItem.LoginInterface;

    public iOSManageItem Interface
    {
        get => _interface;
        set => SetField(ref _interface, value);
    }

    public async Task<string> Login(string? name, string? id)
    {
        if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(id)) return "姓名学号未填写";
        var client = new HttpClient();
        try
        {
            using var result = await client.PostAsJsonAsync($"{_url}/Member/Login", new LoginModel()
                { Name = name, Id = id });
            if (result.StatusCode == HttpStatusCode.NotFound) return "登录失败";
            Jwt = await result.Content.ReadAsStringAsync();
        }
        catch (Exception e)
        {
            client.Dispose();
            var dialog = new ContentDialog()
            {
                Title = "西建大iOS Club工具包",
                Content = e.Message,
                PrimaryButtonText = "Ok"
            };
            await dialog.ShowAsync();
            return "";
        }

        client.Dispose();
        return "登录成功";
    }

    private async void Login()
    {
        var data = await GetMemberData();
        if (data == null) return;
        Items.Clear();
        switch (data.Identity)
        {
            case "Founder":
                Items.Add(iOSManageItem.ClubManageInterface);
                break;
            case "Member":
                Items.Add(iOSManageItem.CentreInterface);
                break;
            default:
                Items.Add(iOSManageItem.CentreInterface);
                Items.Add(iOSManageItem.ClubManageInterface);
                break;
        }

        Interface = iOSManageItem.StartInterface;
    }

    public async Task<iOSMemberModel?> GetMemberData()
    {
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Jwt);
        using var result = await client.GetAsync($"{_url}/Member/GetData");
        if (result.StatusCode == HttpStatusCode.NotFound) return default;
        var memberJsonData = await result.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<iOSMemberModel>(memberJsonData);
    }

    public async Task<string> GetMemberIdentity(LoginModel model)
    {
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Jwt);
        using var result = await client.PostAsJsonAsync($"{_url}/President/GetMemberIdentity", model);
        if (result.StatusCode == HttpStatusCode.NotFound) return "Member";
        return await result.Content.ReadAsStringAsync();
    }

    public async Task<List<SignModel>?> GetAllData()
    {
        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Jwt);
        using var result = await client.GetAsync($"{_url}/President/GetAllData");
        if (result.StatusCode == HttpStatusCode.BadGateway) return default;
        var memberJsonData = await result.Content.ReadAsStringAsync();
        client.Dispose();
        return JsonConvert.DeserializeObject<List<SignModel>>(GZipServer.DecompressString(memberJsonData));
    }

    public async Task<bool> Update(SignModel model, bool isPresident = false)
    {
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Jwt);
        if (isPresident)
        {
            using var result = await client.PostAsJsonAsync($"{_url}/President/Update", model);
            return result.StatusCode == HttpStatusCode.OK;
        }
        else
        {
            using var result = await client.PutAsJsonAsync($"{_url}/Member/Update/{model.UserId}", model);
            return result.StatusCode == HttpStatusCode.OK;
        }
    }

    public async Task<bool> UpdateIdentity(PermissionsModel model)
    {
        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Jwt);
        using var result = await client.PostAsJsonAsync($"{_url}/President/UpdateIdentity",model);
        client.Dispose();
        return result.StatusCode == HttpStatusCode.OK;
    }

    public async Task<bool> Delete(string id)
    {
        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Jwt);
        using var result = await client.DeleteAsync($"{_url}/President/Delete/{id}");
        client.Dispose();
        return result.StatusCode == HttpStatusCode.OK;
    }

    public async Task AddJsonData(string s)
    {
        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Jwt);
        using var result = await client.PostAsJsonAsync($"{_url}/President/AddJsonData", GZipServer.CompressString(s));
        client.Dispose();
    }
}